package com.edu.controller;


import com.edu.client.VodClient;
import com.edu.entity.Video;
import com.edu.service.VideoService;
import com.edu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author mxs
 * @since 2021-10-21
 */
@RestController
@RequestMapping("/edu/video")
@CrossOrigin
public class VideoController {


    @Autowired
    private VideoService videoService;
    /**
     * 注入被调用的客户端
     */
    @Autowired
    private VodClient vodClient;

    //添加课程

    /**
     * 添加小节
     *
     * @param video
     * @return
     */
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody Video video) {
        System.out.println(video);
        videoService.save(video);
        return R.success();
    }

    /**
     * 根据id删除小节
     * 同时删除小节中的视频
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteVideo(@PathVariable String id) {
        //通过小节id获取小节这个对象
        Video video = videoService.getById(id);
        //获取视频的id

        //调用删除方法
        //判断该小节是否有视频
        if (!StringUtils.isEmpty(video.getVideoSourceId())) {
            //如果不为空就删掉视频的id
            vodClient.removeAlyVideo(video.getVideoSourceId());
        }
        //最后删除小节
        videoService.removeById(id);
        return R.success();
    }

    /**
     * 更新小节
     *
     * @param video
     * @return
     */
    @PostMapping("/updateVideo")
    public R updateVideo(@RequestBody Video video) {
        videoService.updateById(video);
        System.out.println(video);
        return R.success();
    }

    /**
     * 根据id返回video
     *
     * @param id video 的 id
     * @return
     */
    @GetMapping("/{id}")
    public R getVideoById(@PathVariable String id) {
        Video video = videoService.getById(id);
        return R.success().data("video", video);
    }

}

